package org.file5.dao.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.file5.dao.ArticleDao;
import org.file5.dao.BaseDao;
import org.file5.domain.Article;
import org.file5.domain.BaseEntity;
import org.file5.domain.Category;
import org.file5.domain.Entity2Entity;
import org.file5.domain.BaseEntity.STATUS;
import org.file5.domain.Entity2Entity.Relation;
import org.file5.util.DataBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.googlecode.objectify.Key;

@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {
	private final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	BaseDao baseDao;

	/**
	 * Gets list of Article
	 * 
	 * @param startPosition
	 * @param maxResult
	 * @param params
	 *            supported Parameters: Category object,STATUS object,
	 * 
	 * @return
	 */
	@Override
	public DataBean<Article> getArticlesBy(int startPosition, int maxResult, Category category, STATUS status) {
		DataBean<Article> result = null;

		if (category != null) {
			DataBean<Entity2Entity<Article, Category>> edb = baseDao.getEntity2EntitiesBy(startPosition, maxResult,
					null, Relation.ARTICLE_IS_CATEGORY_MEMBER, category, status);
			if (!edb.isEmpty()) {
				result = new DataBean<Article>();
				result.setCount(edb.getCount());
				for (Entity2Entity<Article, Category> e2e : edb.getData()) {
					Article a = baseDao.find(e2e.getEntityKey());
					if (a != null) {
						result.getData().add(a);
					} else {
						baseDao.remove(e2e);// no used e2e
					}
				}
			}
		} else { // no params
			if (status != null) {
				result = baseDao.getListByProperties(Article.class, startPosition, maxResult, "status", status.name());
			} else {
				result = baseDao.getListByProperties(Article.class, startPosition, maxResult);
			}
		}

		if (result != null && !result.isEmpty()) {
			for (Article p : result.getData()) {
				p.setAuthor(baseDao.find(p.getAuthorKey()));
				p.setPrimaryCategory(baseDao.find(p.getPrimaryCategoryKey()));
			}
		}

		return result;
	}

}
